package ncut.shumei.dao.impl;

import ncut.shumei.dao.BookDao;
import ncut.shumei.entity.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

@Repository("bookDao")
public class BookDaoImpl implements BookDao {
    
    @Autowired
    private JdbcTemplate jdbcTemplate;

    private final RowMapper<Book> bookRowMapper = (ResultSet rs, int rowNum) -> {
        Book book = new Book();
        book.setIsbn(rs.getString("isbn"));
        book.setName(rs.getString("name"));
        book.setPrice(rs.getDouble("price"));
        book.setAuthor(rs.getString("author"));
        book.setPress(rs.getString("press"));
        return book;
    };

    @Override
    public Book findByIsbn(String isbn) {
        String sql = "SELECT * FROM book WHERE isbn = ?";
        try {
            return jdbcTemplate.queryForObject(sql, new Object[]{isbn}, bookRowMapper);
        } catch (EmptyResultDataAccessException e) {
            System.out.println("未找到ISBN为 " + isbn + " 的图书");
            return null;
        }
    }

    @Override
    public Book findByName(String name) {
        String sql = "SELECT * FROM book WHERE name = ?";
        try {
            return jdbcTemplate.queryForObject(sql, new Object[]{name}, bookRowMapper);
        } catch (EmptyResultDataAccessException e) {
            System.out.println("未找到书名为 " + name + " 的图书");
            return null;
        }
    }

    @Override
    public List<Book> findByNameContainingWeb(String keyword) {
        String sql = "SELECT * FROM book WHERE name LIKE ?";
        List<Book> books = jdbcTemplate.query(sql, new Object[]{"%" + keyword + "%"}, bookRowMapper);
        System.out.println("找到 " + books.size() + " 本包含 '" + keyword + "' 的图书");
        return books;
    }

    @Override
    public void addBook(Book book) {
        String sql = "INSERT INTO book (isbn, name, price, author, press) VALUES (?, ?, ?, ?, ?)";
        try {
            int result = jdbcTemplate.update(sql,
                book.getIsbn(),
                book.getName(),
                book.getPrice(),
                book.getAuthor(),
                book.getPress()
            );
            if (result > 0) {
                System.out.println("成功添加图书：" + book.getName());
            }
        } catch (Exception e) {
            System.err.println("添加图书失败：" + e.getMessage());
            throw e;
        }
    }

    @Override
    public void updateBook(Book book) {
        String sql = "UPDATE book SET name=?, price=?, author=?, press=? WHERE isbn=?";
        try {
            int result = jdbcTemplate.update(sql,
                book.getName(),
                book.getPrice(),
                book.getAuthor(),
                book.getPress(),
                book.getIsbn()
            );
            if (result > 0) {
                System.out.println("成功更新图书：" + book.getName());
            } else {
                System.out.println("未找到要更新的图书：" + book.getIsbn());
            }
        } catch (Exception e) {
            System.err.println("更新图书失败：" + e.getMessage());
            throw e;
        }
    }

    @Override
    public void deleteBook(String isbn) {
        // 首先删除借阅记录
        String deleteBorrowRecords = "DELETE FROM borrow_record WHERE book_isbn = ?";
        jdbcTemplate.update(deleteBorrowRecords, isbn);
        
        // 然后删除图书
        String deleteBook = "DELETE FROM book WHERE isbn = ?";
        try {
            int result = jdbcTemplate.update(deleteBook, isbn);
            if (result > 0) {
                System.out.println("成功删除ISBN为 " + isbn + " 的图书");
            } else {
                System.out.println("未找到ISBN为 " + isbn + " 的图书");
            }
        } catch (Exception e) {
            System.err.println("删除图书失败：" + e.getMessage());
            throw e;
        }
    }

    @Override
    public List<String> findStudentsByBookName(String bookName) {
        String sql = "SELECT DISTINCT s.name FROM student s " +
                    "JOIN borrow_record br ON s.student_id = br.student_id " +
                    "JOIN book b ON br.book_isbn = b.isbn " +
                    "WHERE b.name = ?";
        try {
            List<String> students = jdbcTemplate.query(sql, 
                new Object[]{bookName},
                (rs, rowNum) -> rs.getString("name"));
            System.out.println("找到 " + students.size() + " 个借阅过《" + bookName + "》的学生");
            return students;
        } catch (Exception e) {
            System.err.println("查询借阅学生失败：" + e.getMessage());
            return new ArrayList<>();
        }
    }

    @Override
    public List<Book> findAllBooks() {
        String sql = "SELECT * FROM book";
        return jdbcTemplate.query(sql, bookRowMapper);
    }
} 